package com.lqm.web.controller.admin;

import com.lqm.entity.admin.AdminUser;
import com.lqm.service.admin.AdminUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayDeque;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: CrowdFunding
 * @description 后台用户控制器，包括登录、注册、修改等
 * @author: 权名
 * @create: 2018-12-04 17:27
 */
@RestController
@RequestMapping("/admin")
public class AdminUserController {

    @Autowired
    AdminUserService adminUserService;


    @RequestMapping("/updateUser")
    public Map<String, Object> updateUser(AdminUser adminUser, HttpServletRequest request) {
        System.out.println("updateUser" + adminUser);
        HashMap<String, Object> map = new HashMap<String, Object>();
        boolean save = adminUserService.save(adminUser);
        if (save) {//更新成功
            //更新session
            request.getSession().setAttribute("admin_user", adminUser);
            map.put("code", 0);
            map.put("msg", "修改成功");
        } else {
            map.put("code", 101);
            map.put("msg", "修改失败");
        }
        return map;
    }

    @RequestMapping("/updatePassword")
    public Map<String, Object> updatePassword(String oldPassword, String password, String repassword, HttpServletRequest request) {
        HashMap<String, Object> map = new HashMap<String, Object>();
        //服务器二次校验两次密码是否一致
        if (password.equals(repassword)) {
            AdminUser adminUser = (AdminUser) request.getSession().getAttribute("admin_user");
            String old = DigestUtils.md5DigestAsHex(oldPassword.getBytes());
            if (old.equals(adminUser.getPassword())) {
                //1、执行修改
                adminUser.setPassword(DigestUtils.md5DigestAsHex(password.getBytes()));
                adminUserService.save(adminUser);
                //2、更新session
                request.getSession().setAttribute("admin_user", adminUser);
                map.put("code", 0);
                map.put("msg", "修改成功");
                return map;
            }

        }
        map.put("code", 101);
        map.put("msg", "修改失败");


        return map;
    }


    /**
     * 获取当前用户信息
     */
    @ModelAttribute
    public void getUser(HttpServletRequest request, Model model) {/*@RequestParam(required = false) Integer id*/
        AdminUser user = (AdminUser) request.getSession().getAttribute("admin_user");
        if (user != null) {
            model.addAttribute("adminUser", user);
        }
    }


}
